package com.travel.service.user;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.travel.common.ServerResponse;
import com.travel.dao.tourist_demand.TouristTrabelDemandMapper;
import com.travel.dao.user.TouristUserMapper;
import com.travel.pojo.user.Sign;
import com.travel.pojo.user.TouristUser;
import com.travel.service.WeiXin.WeiXinApi;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class TouristUserServer {

    @Autowired
    TouristUserMapper touristUserMapper;

    @Autowired
    TouristTrabelDemandMapper trabelDemandMapper;

    @Autowired
    WeiXinApi weiXinApi;

    /**
     * 密码用md5加密五次，在别人不知道加密次数的情况下不能反向解密
     */

    /**
     * 登录，进行查询前先将密码加密
     * @param tel 电话号码
     * @param password 用户密码
     */
    public ServerResponse<TouristUser> login(String tel, String password){
        TouristUser t=touristUserMapper.queryTel(tel);
        if (t==null){
            return ServerResponse.createByErrorMessage("手机号错误");
        }
        //传给数据库密码MD5加密进行查询，因为存在数据库的密码也是加密过的
        String pwd=password;
        for (int i = 0; i <=5; i++) {
            pwd=DigestUtils.md5Hex(pwd);
        }
        TouristUser touristUser=touristUserMapper.queryuserTuser(tel,pwd);
        System.out.println("信息"+touristUser);
        if (touristUser==null){
            return ServerResponse.createByErrorMessage("密码错误");
        }
        //将对象中的密码置空返回给前端
        touristUser.setPassword(org.apache.commons.lang3.StringUtils.EMPTY);
        return ServerResponse.createBySuccess("登录成功",touristUser);
    }


    /**
     * 注册
     * @param touristUser 注册信息对象
     */
    public ServerResponse<TouristUser> register(TouristUser touristUser){
        Calendar calendar = new GregorianCalendar();
        TouristUser touristUser1=touristUserMapper.queryByPhone(touristUser.getTel());
        if (touristUser1!=null){
            return ServerResponse.createByErrorMessage("电话号码已被使用");
        }
        //密码MD5加密
        String pwd=touristUser.getPassword();
        for (int i = 0; i <=5; i++) {
            pwd=DigestUtils.md5Hex(pwd);
        }
        touristUser.setPassword(pwd);
        touristUser.setBean_number(30);
        touristUser.setSingin(1);
        //插入数据库
        touristUserMapper.addTuser(touristUser);
        //置空密码
        touristUser.setPassword(org.apache.commons.lang3.StringUtils.EMPTY);
        //添加签到表
        Date date=new Date();
        calendar.setTime(date);
        calendar.add(calendar.DATE,-1);
        date=calendar.getTime();
        Sign sign=new Sign();
        sign.setSigntime(date);
        sign.setContinuity_count(0);
        sign.setSum_count(0);
        sign.setMark(0);
        sign.setUserid(touristUser.getId());
        touristUserMapper.addUserSign(sign);
        //将返回的签到表id返回给前端
        touristUser.setSignid(sign.getId());
        //更新用户signid
        touristUserMapper.updateUserSignIdById(touristUser.getId(),sign.getId());
        return ServerResponse.createBySuccess("注册成功",touristUser);
    }

    /**
     * 修改用户类型（导游和游客）
     * @param id 用户唯一标识
     * @param usertype 目标类型
     */
    public ServerResponse<String> updateUserTypeById(int id,int usertype){
        TouristUser touristUser=touristUserMapper.queryById(id);
        touristUserMapper.updateUserTypeById(id,usertype);
        if (touristUser.getUsertype()!=usertype){
            return ServerResponse.createBySuccseeMessage("修改成功");
        }else {
            return ServerResponse.createByErrorMessage("修改失败");
        }
    }


    /**
     * 文件上传
     * @param file 上传文件
     */
    public String uploadfile(MultipartFile file, HttpServletRequest request) throws IOException {
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path;
        Date dt = new Date();
        Long time = dt.getTime();
        String realPath = "/usr/userimage/"; // 获取保存的路径，本地磁盘中的一个文件夹，这个格式是linux环境中的
        String originalFilename = time.toString().substring(time.toString().length() - 8, time.toString().length());
        originalFilename = originalFilename.concat(".");
        originalFilename = originalFilename.concat(file.getOriginalFilename().toString().substring(file.getOriginalFilename().toString().indexOf(".") + 1));
        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realPath, originalFilename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String url=basePath + "/static/image/" + originalFilename;
        return url;
    }

    /**
     * 游客账号修改密码，传入旧密码需要和数据库中的密码相同
     * @param id 用户唯一标识
     * @param usedpwd 旧密码
     * @param newpwd 新密码
     */
    public ServerResponse<String> updatepwdByUsedpwd(int id,String usedpwd,String newpwd){
        TouristUser touristUser=touristUserMapper.queryById(id);
        String pwd=usedpwd;
        for (int i = 0; i <= 5; i++) {
            pwd=DigestUtils.md5Hex(pwd);
        }
        //新密码传入用MD5加密
        String pwd1=newpwd;
        for (int i = 0; i <= 5; i++) {
            pwd1=DigestUtils.md5Hex(pwd1);
        }
        if (pwd.equals(touristUser.getPassword())){

            Map<String,Object> map=new HashMap<>();
            map.put("id",id);
            map.put("tpwd",pwd1);
            touristUserMapper.updateTuserpwd(map);
            return ServerResponse.createBySuccseeMessage("密码修改成功");
        }
        return ServerResponse.createByErrorMessage("旧密码错误");
    }

    /**
     * 根据用户id修改密码，用于发送验证码修改密码
     * @param phoneNumber 用户唯一表示
     * @param newpwd 用户新密码
     */
    public ServerResponse<String> updatapwdByTel(String phoneNumber,String newpwd){
        String pwd=newpwd;
        for (int i = 0; i <= 5; i++) {
            pwd=DigestUtils.md5Hex(pwd);
        }
        TouristUser touristUser= touristUserMapper.queryByPhone(phoneNumber);
        touristUserMapper.updateUserPwdByPhone(phoneNumber,pwd);
        TouristUser touristUser1=touristUserMapper.queryByPhone(phoneNumber);
        if (!touristUser.getPassword().equals(touristUser1.getPassword())){
            return ServerResponse.createBySuccseeMessage("修改成功");
        }
        return ServerResponse.createByErrorMessage("修改失败");
    }
    /**
     * 修改除tid,密码，用户类型的其他信息
     * @param touristUser 用户修改信息对象
     */
    public ServerResponse<String> updateinformation(TouristUser touristUser){
       int a= touristUserMapper.updateTinformation(touristUser);
        if (a==1){
            return ServerResponse.createBySuccseeMessage("修改成功");
        }
        return ServerResponse.createByErrorMessage("修改失败");
    }

    /**
     * 修改用户头像
     * @param id 用户唯一标识
     * @param file 用户上传的图片
     */
    public ServerResponse<Map<String,Object>> updateImageurl(int id,MultipartFile file, HttpServletRequest request) throws IOException {
        String url=uploadfile(file,request);
        touristUserMapper.updateFileUrl(url,id);
        Map<String,Object> map=new HashMap<>();
        map.put("imageurl",url);
        return ServerResponse.createBySuccess(map);
    }

    /**
     * 绑定用户授权接收消息后的设备id
     * @param id 用户id
     * @param clientid 用户设备id
     */
    public ServerResponse<String> updateClientidById(int id,String clientid){
        int a=touristUserMapper.updateUserClientidById(id, clientid);
        if (a==0){
            return ServerResponse.createByErrorMessage("clientID更新失败");
        }else {
            return ServerResponse.createBySuccseeMessage("clientID更新成功");
        }

    }

    /**
     * 上传团头图
     * @param city 城市名
     * @param file 用户上传的图片
     */
    public ServerResponse<Map<String,Object>> addImageurl(String city,MultipartFile file, HttpServletRequest request) throws IOException {
        String url=uploadfile(file,request);
        trabelDemandMapper.insertImage(city,url);
        Map<String,Object> map=new HashMap<>();
        map.put("imageurl",url);
        return ServerResponse.createBySuccess(map);
    }

    /**
     * 增加U豆
     * @param userid 用户id
     * @param addbeannumber 增加数量
     */
    public ServerResponse<Integer> addUBean(int userid,int addbeannumber){
        TouristUser touristUser=touristUserMapper.queryById(userid);
        int a=touristUserMapper.addBeanNumberById(userid,touristUser.getBean_number()+addbeannumber);
        if (a==0){
            return ServerResponse.createByErrorMessage("U豆增加失败");
        }else {
            return ServerResponse.createBySuccess("U豆增加成功,更新后数量为:",touristUser.getBean_number()+addbeannumber);
        }
    }

    /**
     * 查询签到信息
     * @param userid 用户id
     */
    public ServerResponse<Sign> querySignInformation(int userid){
        Sign userSign=touristUserMapper.querySignByUserId(userid);
        return ServerResponse.createBySuccess("签到数据为",userSign);
    }

    /**
     * 用户签到
     * @param userid 用户id
     * @param signid 签到信息id
     *  Mark 签到信息，0表示未签到，1表示已签到
     */
    public ServerResponse<Map<String,Object>> userSign(int userid,int signid){
        Calendar calendar = new GregorianCalendar();

        Sign sign=touristUserMapper.querySignByUserId(userid);
        System.out.println(sign);
        sign.setMark(1);
        sign.setSum_count(sign.getSum_count()+1);

        //取今天的日期，转换为int类型
        Date today=new Date();
        calendar.setTime(today);
        calendar.add(calendar.DATE,0);
        today=calendar.getTime();
        //取具体几号，转化int型
        SimpleDateFormat formatter2 = new SimpleDateFormat("dd");
        String todaydate= formatter2.format(today);
        int todaydate1=new Integer(todaydate);

        //取出数据库中上一次签到的时间，取出签到日期
        Calendar calendar1 = new GregorianCalendar();
        Date yesterday=sign.getSigntime();
        calendar1.setTime(yesterday);
        yesterday=calendar1.getTime();
        SimpleDateFormat formatter = new SimpleDateFormat("dd");
        String day= formatter.format(yesterday);
        //转化为int型
        int yesterdaydate=new Integer(day);

        //取出上一次签到日期的第一位字节用于判断是否为0，让后转化为int
        String firstOneByte= (String) day.subSequence(0,1);
        int yesterdaydatefirstByte=new Integer(firstOneByte);

        switch (yesterdaydatefirstByte){
            case 0:
                //取出上一次签到日期的第二位字节，让后转化为int
                String secondByte=day.substring(1);
                int b=new Integer(secondByte);
                if (todaydate1-b==1){
                    sign.setContinuity_count(sign.getContinuity_count()+1);
                }else if(todaydate1-b==0){
                    return ServerResponse.createByErrorMessage("今日已经签到");
                }else {
                    sign.setContinuity_count(0);
                }
                break;

            default:
                if (todaydate1-yesterdaydate==1){
                    sign.setContinuity_count((sign.getContinuity_count())+1);
                }else if(todaydate1-yesterdaydate==0){
                    return ServerResponse.createByErrorMessage("今日已经签到");
                }else {
                    sign.setContinuity_count(0);
                }
        }
        sign.setSigntime(today);
        int a=touristUserMapper.userSign(sign,userid);
        if (a!=0){
            TouristUser user=touristUserMapper.queryById(userid);
            //连续签到奖励
            if (sign.getContinuity_count()<=3){
                touristUserMapper.reduceBeanNUmberById(userid,user.getBean_number()+10);
            }else if(sign.getContinuity_count()<3 && sign.getContinuity_count()<=6){
                touristUserMapper.reduceBeanNUmberById(userid,user.getBean_number()+15);
            }else if(sign.getContinuity_count()>=7){
                touristUserMapper.reduceBeanNUmberById(userid,user.getBean_number()+20);
            }
            TouristUser user1=touristUserMapper.queryById(userid);
            Map<String,Object> data=new HashMap();
            data.put("sign",sign);
            data.put("beanNumber",user1.getBean_number());
            return ServerResponse.createBySuccess("签到成功,更新数据：",data);
        }else {
            return ServerResponse.createByErrorMessage("签到失败");
        }

    }


    /**
     * 利用阿里云发送短信验证码
     * @param phoneNumber 接收短信的电话号码
     * @param code 随机验证码
     */
    public boolean sendMsg(String phoneNumber,Map<String,Object> code){
        //连接阿里云
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4G3nsoWfFsmZyJ7rGz6D", "wITuyTLPraTYNbcbZOHYcyfJkH1eog");
        IAcsClient client = new DefaultAcsClient(profile);
        //构建请求
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        //自定义参数（手机号，签名，模板,验证码）
        request.putQueryParameter("PhoneNumbers", phoneNumber);
        request.putQueryParameter("SignName","悠游");
        request.putQueryParameter("TemplateCode","SMS_189621290");
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(code));

        try {
                CommonResponse response = client.getCommonResponse(request);
                System.out.println(response.getData());
                return response.getHttpResponse().isSuccess();
            } catch (ServerException e) {
                e.printStackTrace();
            } catch (ClientException e) {
                e.printStackTrace();
            }
            return false;
    }

}
